package com.techsen.tsweb.sys.web.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.techsen.tsweb.core.domain.JsonResult;
import com.techsen.tsweb.core.util.ValidUtil;
import com.techsen.tsweb.core.util.sql.Pager;
import com.techsen.tsweb.sys.domain.Dict;
import com.techsen.tsweb.sys.service.DictService;

@Controller
@RequestMapping("/sys/dict")
public class DictController {

    @Resource
    private DictService dictService;
    
    /**
     * 根据字段值查找字典集合
     */
    @RequestMapping("/list-by-field")
    public @ResponseBody List<Dict> listByField(String field) {
        List<Dict> list = new ArrayList<Dict>();
        if (ValidUtil.isValid(field)) {
            list = this.dictService.getListByEntity(new Dict().setField(field));
        }
        return list;
    }
    
    /**
     * 进入字典管理界面
     */
    @RequestMapping
    public String index(String menuId, Model model) {
        model.addAttribute("menuId", menuId);
        return "sys/dict";
    }
    
    /**
     * 分页查询字典
     */
    @RequestMapping("/pager")
    public @ResponseBody Pager<Dict> pager(@RequestBody Pager<Dict> pager) {
        return this.dictService.findByPager(pager);
    }
    
    /**
     * 进入添加字典界面
     */
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add() {
        return "sys/dict-add";
    }
    
    /**
     * 添加字典
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public @ResponseBody JsonResult add(Dict dict) {
        this.dictService.add(dict);
        return new JsonResult(dict);
    }
    
    /**
     * 删除字典
     */
    @RequestMapping("/delete")
    public @ResponseBody JsonResult delete(String id) {
        this.dictService.delete(id);
        return new JsonResult(id);
    }
    
    /**
     * 进入修改字典界面
     */
    @RequestMapping(value = "/update", method = RequestMethod.GET)
    public String update(String dictId, Model model) {
        Dict dict = this.dictService.get(dictId);
        model.addAttribute("dict", dict);
        return "sys/dict-update";
    }
    
    /**
     * 修改字典
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public @ResponseBody JsonResult update(Dict dict) {
        this.dictService.update(dict);
        return new JsonResult(dict);
    }
    
}
